package com.sky.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class userLoginServiceImpl implements UserLoginService {

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    private static final String URL ="https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 用户登录
     * @return
     */
    @Override
    public UserLoginVO userLogin(UserLoginDTO dto) {

        HashMap pram = new HashMap();
        pram.put("appid",weChatProperties.getAppid());
        pram.put("secret",weChatProperties.getSecret());
        pram.put("js_code",dto.getCode());
        pram.put("grant_type","authorization_code");

        String response = HttpClientUtil.doGet(URL,pram);

        //得到openid
        JSONObject jsonObject = JSON.parseObject(response);
        String openid = jsonObject.getString("openid");
        //根据openid判断登录用户是否登陆成功，
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //登录成功，根据openid查询是否有这个用户

        User user = userMapper.getUser(openid);
        if(user==null){
            //说明是新用户，存入数据库
             user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.addUser(user);
        }
        // 在数据库返回该用户的id值
        Long userId = user.getId();
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",userId);
        //获取session key 和 openid,获取令牌
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                                       jwtProperties.getUserTtl(),claims);


        return new UserLoginVO(userId,openid,jwt);
    }
}
